﻿namespace PlugNT.Common.Http
{
    using System;
    using System.Data;
    using System.Text;
    using System.Web;

    public class Document
    {
        public static void Export(DataTable dataTable, int eFlag, string fileName)
        {
            HttpResponse resp = HttpContext.Current.Response;
            resp.ContentEncoding = Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            StringBuilder colHeaders = new StringBuilder();
            int i = 0;
            DataRow[] myRow = dataTable.Select("");
            if (eFlag == 1)
            {
                i = 0;
                while (i < dataTable.Columns.Count)
                {
                    if (i == (dataTable.Columns.Count - 1))
                    {
                        colHeaders.Append(dataTable.Columns[i].Caption.ToString() + "\n");
                    }
                    else
                    {
                        colHeaders.Append(dataTable.Columns[i].Caption.ToString() + "\t");
                    }
                    i++;
                }
                resp.Write(colHeaders.ToString());
                foreach (DataRow row in myRow)
                {
                    StringBuilder lsItem = new StringBuilder();
                    for (i = 0; i < dataTable.Columns.Count; i++)
                    {
                        if (i == (dataTable.Columns.Count - 1))
                        {
                            lsItem.Append(row[i].ToString() + "\n");
                        }
                        else
                        {
                            lsItem.Append(row[i].ToString() + "\t");
                        }
                    }
                    resp.Write(lsItem.ToString());
                }
            }
            else if (eFlag == 2)
            {
                resp.Write(dataTable.DataSet.GetXml());
            }
            resp.End();
        }
    }
}

